import { Button, Modal, Table, message } from 'antd'
import React, { useState, useEffect } from 'react'
import { ExclamationCircleFilled } from '@ant-design/icons';
import * as classRoom from '../../../api/base/classRoom'
import { BaseGeneraForm } from '../../../components'
const ClassRoom: React.FC = () => {
  const [dataSource, setDataSource] = useState<any[]>([])
  const [formData, setFormData] = useState<any>()
  const [isAdd, setIsAdd] = useState<boolean>(false)
  const [open, setOpen] = useState<boolean>(false)

  const formDataConfig = [
    {
      type: 'Input',
      label: '教室名称',
      fieldName: 'class_room_name',
      placeholder: '请输入教室名称'
    },
    {
      type: 'InputNumber',
      label: '人数',
      fieldName: 'capacity',
      placeholder: '请输入人数'
    }
  ]

  const getList = async () => {
    const res = await classRoom.list().catch(err => {
      console.log(err)
    })
    if (res.success) {
      setDataSource(res.data)
    }
  }

  useEffect(() => { getList() }, [])

  const add = () => {
    setIsAdd(true)
    setOpen(true)
  }
  const edit = (val: any) => {
    setIsAdd(false)
    setOpen(true)
    setFormData(val)
  }
  const del = (val: any) => {
    Modal.confirm({
      title: '确定删除',
      icon: <ExclamationCircleFilled />,
      okText: '是',
      cancelText: '否',
      onOk() {
        classRoom.del(val.id).then(res => {
          if (res.success) {
            getList()
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  const emitOnFinish = async (val: any, isAdd: boolean) => {
    let res = null
    if (isAdd) {
      res = await classRoom.created(val).catch(err => {
        if (err.data.data.indexOf('key')) {
          message.warning('教室名称重复')
        }
      })

    } else {
      res = await classRoom.update(formData.id, val).catch(err => {
        console.log(err)
      })
    }
    if (res && res.success) {
      getList()
      setOpen(false)
      setFormData(null)
    }
  }

  const columns = [
    {
      title: '教室名称',
      dataIndex: 'class_room_name',
    },
    {
      title: '人数',
      dataIndex: 'capacity',
    },
    {
      title: '操作',
      key: 'option',
      render: (_: any, record: any) => (
        <>
          <Button type="primary" onClick={() => edit(record)}>编辑</Button>
          <>&nbsp;</>
          <Button type="primary" onClick={() => del(record)}>删除</Button>
        </>
      ),
    },
  ]
  return (
    <>
      <Button onClick={add}>添加</Button>
      <Table dataSource={dataSource} columns={columns} pagination={{ hideOnSinglePage: true }} rowKey="id" />

      <BaseGeneraForm
        title="教室设置"
        open={open}
        formData={formData}
        isAdd={isAdd}
        onCancel={() => setOpen(false)}
        formDataConfig={formDataConfig}
        footer={null}
        emitOnFinish={emitOnFinish}
      />
    </>
  )
}

export default ClassRoom